package cn.jdy.plugins.wap;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.plugins.entity.Doc;
import cn.jdy.plugins.entity.Download;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.DocService;
import cn.jdy.plugins.service.DownloadService;

/**
 * 营销智库控制类
 *
 * @author YangYi
 */
@Controller
@RequestMapping("/doc")
public class DocCtrl extends BaseCtrl {
    @Autowired
    private DocService docService;
    @Autowired
    private DownloadService downloadService;

    /**
     * 营销智库列表
     *
     * @param entity
     * @param s
     * @return
     */
    @RequestMapping("")
    public ModelAndView list(Doc entity, String s, boolean m, String title) {
        ModelAndView mv = new ModelAndView(super.t + "/doc/docList");
        try {
            /*//设置分页信息
            if (entity.getiDisplayLength() == 0) entity.setiDisplayLength(5);                //默认长度5
            if (entity.getPageNo() <= 0) entity.setPageNo(1);                                  //默认页数1
            entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength()); //显示起始索引

            if (m) entity.setUserId(getMember(false).getId());
            else {
                if (s != null && s.length() > 0) entity.setKeyword(s);
                entity.setStatus("1");
            }

            Filter filter = new Filter();
            filter.addCondition("status", "1");
            mv.addObject("doctotal", docService.count(filter));

            mv.addObject("dataList", docService.query(entity));
            mv.addObject("total", docService.count(entity));
            mv.addObject("pageNo", entity.getPageNo());
            mv.addObject("size", entity.getiDisplayLength());*/
            mv.addObject("bizClass", super.bizClass(GlobalConstant.TYPE_DOC));
//            mv.addObject("entity", entity);
//            mv.addObject("keywords", s);
//            mv.addObject("title", title);
        } catch (Exception e) {
            BaseLog.e(this.getClass(), "list", e);
        }
        return mv;
    }

    /**
     * 营销智库列表
     *
     * @param entity
     * @param s
     * @return
     */
    @RequestMapping("/loadMore/{index}")
    @ResponseBody
    public Map<String, Object> loadMore(@PathVariable("index") int index, Doc entity, String s, boolean m, String title) {
        Map<String, Object> resp = new HashMap<>();
        try {
            //设置分页信息
            if (entity.getiDisplayLength() == 0) entity.setiDisplayLength(5);                //默认长度5
            if (index <= 0) index = 1;                                  //默认页数1
            entity.setPageNo(index);
            entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength()); //显示起始索引

            if (m) entity.setUserId(getMember(false).getId());
            else {
                if (s != null && s.length() > 0) entity.setKeyword(s);
                entity.setStatus("1");
            }
            List dataList = docService.query(entity);
            if (dataList != null && dataList.size() > 0) {
                resp.put("dataList", dataList);
                resp.put("statusCode", 200);
            } else {
                resp.put("statusCode", 400);//加载完毕
            }
        } catch (Exception e) {
            BaseLog.e(this.getClass(), "list", e);
        }
        return resp;
    }

    /**
     * 查看智库详情
     *
     * @param id
     * @return
     */
    @RequestMapping("{id}")
    public ModelAndView detail(@PathVariable long id, String title) {
        ModelAndView mv = new ModelAndView(super.t + "/doc/docDetail");
        try {
            mv.addObject("entity", docService.find(id));
            mv.addObject("bizClass", super.bizClass(GlobalConstant.TYPE_DOC));
            //增加一次访问量
            docService.addOneTime(id, 'r');
            mv.addObject("doctotal", docService.count("status", "1"));
            mv.addObject("hotData", docService.queryTops("readTimes", false));
            mv.addObject("newData", docService.queryTops("createTime", false));
            mv.addObject("title", title);
        } catch (Exception e) {
            BaseLog.e(this.getClass(), "detail", e);
        }
        return mv;
    }

    /**
     * 判断是否符合下载条件
     *
     * @param id
     * @return
     */
    @RequestMapping("/check/{id}")
    @ResponseBody
    public Map<String, Object> check(@PathVariable long id) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            Member member = getMember(true);
            if (member != null) {
                Doc doc = docService.find(id);
                if (doc != null) {
                    //判断此智库是否是当前用户提供的，如果是当前用户提供
                    if (doc.getScore() == 0 || String.valueOf(member.getId()).equals(doc.getUserId())) {
                        jsonMap.put("statusCode", 200);
                    } else {
                        //判断用户是否下载过此文件
                        if (downloadService.isDownload(member.getId(), id)) {
                            jsonMap.put("statusCode", 200);
                        } else {
                            if (member.getScore() != null && member.getScore() >= doc.getScore()) {
                                jsonMap.put("statusCode", 201);
                                jsonMap.put("msg", "本地下载将会扣除您" + doc.getScore() + "积分，是否下载？");
                            } else {
                                jsonMap.put("statusCode", 501);
                                jsonMap.put("msg", "您的积分不够！");
                            }
                        }
                    }
                } else {
                    throw new RuntimeException("查询智库异常：" + member.getId());
                }
            } else {
                jsonMap.put("statusCode", 502);
                jsonMap.put("msg", "请登录后下载！");
            }
        } catch (Exception e) {
            jsonMap.put("statusCode", 500);
            jsonMap.put("msg", "对不起，不支持下载！");
            BaseLog.e(this.getClass(), "查询错误", e);
        }
        return jsonMap;
    }

    /**
     * 智库下载
     *
     * @param id
     * @param response
     */
    @RequestMapping("/down/{id}")
    @ResponseBody
    public void down(@PathVariable long id, HttpServletResponse response) {
        Doc doc = docService.find(id);
        if (doc == null) return;
        String fileUrl = doc.getFileUrl();
        if (fileUrl == null || fileUrl.isEmpty()) return;
        File file = new File(GlobalConstant.PROJECT_UPLOAD_PATH + fileUrl);
        if (!file.exists()) {
            BaseLog.e(this.getClass(), "找不到文件:" + file);
            return;
        }

        Member member = getMember(true);
        //判断用户是否下载过此文件
        if (downloadService.isDownload(member.getId(), id)) {
            downloadService.addOneTime(member.getId(), id);
        } else {
            Download download = new Download();
            download.setDocId(doc.getId());
            download.setUserId(member.getId());
            download.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
            download.setCount(1);
            if (!member.getId().equals(doc.getUserId())) {
                download.setScore(doc.getScore());
                member.setScore(member.getScore() - doc.getScore());
                try {
                    memberService.update(member);
                } catch (Exception e) {
                    BaseLog.e(this.getClass(), "扣除会员积分异常：" + member.getId(), e);
                }
                try {
                    member = memberService.find(doc.getUserId());
                    if (member != null) {
                        member.setScore(member.getScore() + doc.getScore());
                        memberService.update(member);
                    }
                } catch (Exception e) {
                    BaseLog.e(this.getClass(), "赠送会员积分异常：" + doc.getUserId(), e);
                }
            }
            downloadService.save(download);
        }

        // 增加一次下载次数
        docService.addOneTime(id, 'd');

        OutputStream out = null;
        InputStream inStream = null;
        try {
            //准备下载文件
            response.reset();
            request.setCharacterEncoding("UTF-8");
            int extension = fileUrl.lastIndexOf(".");
            String name = doc.getTitle() + (extension > -1 ? fileUrl.substring(extension) : "");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            int i = -1;
            inStream = new FileInputStream(file);
            out = response.getOutputStream();
            while ((i = inStream.read()) != -1) {
                out.write(i);
            }
            out.flush();
        } catch (Exception e) {
            BaseLog.e(this.getClass(), "down:输出流输出时错误!", e);
        } finally {
            try {
                inStream.close();
                out.close();
            } catch (IOException e) {
                BaseLog.e(this.getClass(), "关闭流时出错", e);
            }
        }
    }

}
